import { View, Image, Text, Input } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { Component, ReactNode } from "react";
import html2canvas from "html2canvas";
import pay from "../../image/pay.png";
import "./index.less";

interface DrawObject {
  text: string;
  x: number;
  y: number;
  fontSize: number;
}

interface EditorState {
  showModal: boolean;
  text: string;
  drawObjects: DrawObject[];
  fontSize: number;
  successfully: boolean;
  url: string;
}

export default class Editor extends Component<any, EditorState> {
  editorMain: HTMLElement | null;
  constructor(props) {
    super(props);
    this.state = {
      showModal: false,
      text: "",
      drawObjects: [],
      fontSize: 25,
      successfully: false,
      url: "",
    };
  }

  componentDidMount(): void {
    this.editorMain = document.getElementById("editor_main");
  }

  isWeixin() {
    return /micromessenger/i.test(navigator.userAgent);
  }

  editorText() {
    this.showEditorModal(false);
    const ele = document.createElement("div");
    ele.className = "newText";
    const html = `<span  size=${this.state.fontSize} style="font-size:${this.state.fontSize}px">${this.state.text}<span>`;
    ele.innerHTML = html;
    ele.ontouchmove = this.onMove;
    this.editorMain?.appendChild(ele);
  }

  editorImage() {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempPath = res.tempFilePaths[0];
        const ele = document.createElement("div");
        ele.className = "newText";

        const html = `<img  src='${tempPath}' crossOrigin='anonymous' style='width:150px;height:150px'/><div class='btns' id='btns'><span class='narrow-down' id='narrow-down'>-</span><span class='increase' id='increase'>+</span><span id='delete'>x<span></div><div class='btns2' id='btns2'><span class='narrow-down2' id='narrow-down2'>-</span><span class='increase2' id='increase2'>+</span><span id='delete2'>x<span></div>`;
        ele.innerHTML = html;
        ele.ontouchmove = this.onImageMove;
        this.editorMain?.appendChild(ele);

        const narrow = document.getElementById("narrow-down");
        if (narrow) {
          narrow.onclick = function (e) {
            const { target } = e;
            const img = (target as any)?.parentNode.parentNode.children[0];
            const width = img.offsetWidth - 5;
            const height = img.offsetHeight;
            img.style = `width:${width}px;height:${height}px`;
          };
        }

        const narrow2 = document.getElementById("narrow-down2");
        if (narrow2) {
          narrow2.onclick = function (e) {
            const { target } = e;
            const img = (target as any)?.parentNode.parentNode.children[0];
            const width = img.offsetWidth;
            const height = img.offsetHeight - 5;
            img.style = `width:${width}px;height:${height}px`;
          };
        }

        const increase = document.getElementById("increase");
        if (increase) {
          increase.onclick = function (e) {
            const { target } = e;
            const img = (target as any)?.parentNode.parentNode.children[0];
            const width = img.offsetWidth + 5;
            const height = img.offsetHeight;
            img.style = `width:${width}px;height:${height}px`;
          };
        }

        const increase2 = document.getElementById("increase2");
        if (increase2) {
          increase2.onclick = function (e) {
            const { target } = e;
            const img = (target as any)?.parentNode.parentNode.children[0];
            const width = img.offsetWidth;
            const height = img.offsetHeight + 5;
            img.style = `width:${width}px;height:${height}px`;
          };
        }

        const dele = document.getElementById("delete");
        if (dele) {
          dele.onclick = function (e) {
            const { target } = e;
            const node = (target as any)?.parentNode;
            node.style = "display:none;";
            const node2 = (target as any)?.parentNode.parentNode.children[2];
            node2.style = "display:none;";
          };
        }

        const dele2 = document.getElementById("delete2");
        if (dele2) {
          dele2.onclick = (e) => {
            const { target } = e;
            this.editorMain?.removeChild(
              (target as any)?.parentNode.parentNode
            );
          };
        }
      },
    });
  }

  showEditorModal(flag) {
    this.setState({
      showModal: flag,
    });
  }

  onMove(e) {
    e.preventDefault();
    const { clientX, clientY, target } = e.touches[0];
    const size = target.getAttribute("size");
    target.parentNode.style = `top:${
      clientY - (target.parentNode.parentNode?.offsetTop || 0) - size
    }px;left:${
      clientX -
      (target.parentNode.parentNode?.offsetLeft || 0) -
      target.offsetWidth / 2
    }px;`;
  }

  onImageMove(e) {
    e.preventDefault();
    const { clientX, clientY, target } = e.touches[0];
    const { nodeName } = target;
    if (nodeName !== "IMG") {
      return;
    }
    target.parentNode.style = `top:${
      clientY -
      (target.parentNode.parentNode?.offsetTop || 0) -
      target.offsetHeight / 2
    }px;left:${
      clientX -
      (target.parentNode.parentNode?.offsetLeft || 0) -
      target.offsetWidth / 2
    }px;`;
  }

  saveImg() {
    const element = document.getElementById("editor_main");
    Taro.showLoading({
      title: "保存中",
    });
    if (element) {
      // 使用 html2canvas 将 HTML 元素转换为 Canvas
      html2canvas(element, {
        useCORS: true,
        allowTaint: true,
      }).then((canvas) => {
        // 将 Canvas 转换为图片链接
        const dataUrl = canvas.toDataURL("image/png");
        this.setState({
          url: dataUrl,
          successfully: true,
        });
        if (this.isWeixin()) {
          Taro.hideLoading();
          return;
        }
        Taro.saveImageToPhotosAlbum({
          filePath: dataUrl,
          success: () => {
            Taro.hideLoading();
            Taro.showToast({
              title: "保存成功",
              icon: "none",
              duration: 3000,
            });
          },
        });
      });
    }
  }

  render(): ReactNode {
    const { image } = Taro.getCurrentInstance().router?.params || {};

    return (
      <View className="editor_index">
        <View className="navigatorBar">
          <Text>编辑壁纸</Text>
        </View>
        <View
          id="editor_main"
          className="editor_main"
          style={{
            height: 180,
          }}
        >
          <Image
            src={image + `?${new Date().getTime()}` || ""}
            className="background_img"
            // @ts-ignore
            crossOrigin="anonymous"
          ></Image>
        </View>
        <View className="tips">
          <Text>
            Tips: 添加的文字和图片都可以移动调整位置。图片可以使用
            -(上一行操作宽，下一行操作高) 缩小，+(上一行操作宽，下一行操作高)
            放大, x(上一行) 隐藏按钮, x(下一行) 删除图片。感谢使用,祝99。
          </Text>
          <Image
            src={pay}
            style={{ width: 100, height: 150 }}
            onLongPress={() => {
              Taro.saveImageToPhotosAlbum({
                filePath: pay,
                success: () => {
                  Taro.showToast({
                    title: "保存成功",
                    icon: "none",
                    duration: 3000,
                  });
                },
              });
            }}
          ></Image>
          <Text
            style={{
              fontSize: 12,
            }}
          >
            (长按保存，请我喝杯奶茶吧。)
          </Text>
        </View>
        <View className="editor_ability">
          <Text
            className="editor_text"
            onClick={this.showEditorModal.bind(this, true)}
          >
            插入文本
          </Text>
          <Text className="editor_text" onClick={this.editorImage.bind(this)}>
            插入图片
          </Text>
        </View>
        <View className="editor_bottom">
          <Text className="editor_text" onClick={this.saveImg.bind(this)}>
            立即生成
          </Text>
        </View>
        {this.state.showModal && (
          <View className="editor_modal">
            <Text className="title">请输入文字</Text>
            <Input
              placeholder="请输入"
              value={this.state.text}
              onInput={(e) => {
                this.setState({
                  text: e.detail.value,
                });
              }}
              className="input"
              placeholderClass="input"
              placeholderTextColor="orange"
              placeholderStyle="color:orange;"
            ></Input>
            <Input
              type="number"
              placeholder="请输入字号"
              value={this.state.fontSize.toString()}
              onInput={(e) => {
                this.setState({
                  fontSize: +e.detail.value,
                });
              }}
              className="input"
              placeholderClass="input"
              placeholderTextColor="orange"
              placeholderStyle="color:orange;"
            ></Input>
            <View className="botton">
              <Text onClick={this.showEditorModal.bind(this, false)}>取消</Text>
              <Text onClick={this.editorText.bind(this)}>确认</Text>
            </View>
          </View>
        )}

        {this.isWeixin() && this.state.successfully && (
          <View className="isWexin">
            <Image
              src={this.state.url}
              onLongPress={() => {
                Taro.saveImageToPhotosAlbum({
                  filePath: this.state.url,
                  success: () => {
                    Taro.showToast({
                      title: "保存成功",
                      icon: "none",
                      duration: 3000,
                    });
                  },
                });
              }}
            ></Image>
            <Text>(长按图片保存)</Text>
          </View>
        )}
      </View>
    );
  }
}
